#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>


#define ERROR_CHECK(ret, funcName) \
do{ \
    if(ret!=0) \
    {\
        printf("%s : %s\n", funcName, strerror(ret)); \
        exit(1); \
    }\
}while(0);

void *threadFunc(void *arg)
{
    printf("threadFunc thread\n");
    usleep(10); //这里睡觉就让出cpu，被杀了，所以只打印了第一句
    int *pInt=(int *)arg;
    printf("*pInt = %d\n",*pInt);

    pthread_exit(NULL); //让子线程主动退出
}

int main()
{
    pthread_t thid;
    int number=100;
    int ret=pthread_create(&thid, NULL, threadFunc, &number);
    ERROR_CHECK(ret, "pthread_create");

    printf("main thread\n");
    printf("main thread id: %ld\n",pthread_self());
    
    //主线程杀死子线程
    ret = pthread_cancel(thid);
    ERROR_CHECK(ret,"pthread_cancel");
    //但是子线程依旧可以完整打出，所以cancel在子线程执行完后才杀
    //所以要让子线程睡觉

    ret = pthread_join(thid,NULL);  //让主线程阻塞等待thid这个线程执行结束
    ERROR_CHECK(ret,"pthread_join");
    
    return 0;
}

